﻿namespace WLFramework.Web.Binder.ValueProvider
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Linq;
    using System.Text;

    public class NameValueCollectionValueProvider : IValueProvider
    {
        private NameValueCollection values;
        private Dictionary<string, ValueProviderResult> caches = new Dictionary<string, ValueProviderResult>();

        public NameValueCollectionValueProvider(NameValueCollection collection)
        {
            Shield.AssertNotNull(ref collection, "collection");
            this.values = collection;
        }

        public ValueProviderResult GetValue(string key)
        {
            Shield.AssertNotNull(ref key, "key");

            ValueProviderResult result;
            if (this.caches.TryGetValue(key, out result))
            {
                return result;
            }

            string[] valueAsString = this.values.GetValues(key);
            if (valueAsString == null)
            {
                return null;
            }

            result = new ValueProviderResult(valueAsString);
            this.caches[key] = result;
            return result;
        }
    }
}
